import * as types from './types'

export const state = {
  releaseLoan: {
    loans: [],
    loading: false,
    pageSize: 10,
    total: 0,
    curPage: 1
  }
}

export const getters = {
  releaseLoan_loans: state => state.releaseLoan.loans,
  releaseLoan_loading: state => state.releaseLoan.loading,
  releaseLoan_pageSize: state => state.releaseLoan.pageSize,
  releaseLoan_total: state => state.releaseLoan.total,
  releaseLoan_curPage: state => state.releaseLoan.curPage
}

export const actions = {
  getReleaseLoans({
    commit
  }, payload) {
    commit(types.GET_RELEASE_LOANS, payload)
  },
  releaseLoan({
    commit
  }, payload) {
    commit(types.RELEASE_LOANS, payload)
  }
}

export const mutations = {
  /**
   * 获取标的放款列表
   * 
   * @param {any} state 
   * @param {any} {
   *     vm,
   *     page
   *   } 
   */
  [types.GET_RELEASE_LOANS](state, {
    vm,
    page
  }) {
    state.releaseLoan.loading = true;
    const params = {
      limit: state.releaseLoan.pageSize
    };
    params.start = page ? page : state.releaseLoan.curPage;

    vm.$ajax.get('/loan/showCheckedLoan', {
        params: params
      })
      .then(res => {
        let data = res.data
        if (data && data.status == vm.$appConfig.success) {
          state.releaseLoan.loans = data.list;
          state.releaseLoan.total = data.total;
          state.releaseLoan.pageSize = data.pageSize;
          state.releaseLoan.curPage = data.curPage;
        } else {
          state.releaseLoan.loans = [];
        }
        console.log(res.data)
        state.releaseLoan.loading = false;
      })
      .catch(err => {
        state.releaseLoan.loans = [];
        state.releaseLoan.loading = false;

        vm.$notify.error({
          title: '失败',
          message: '获取标的放款列表失败'
        });
        console.error(err);
      });
  },
  /**
   * 标的放款
   * 
   * @param {any} state 
   * @param {any} {
   *     vm,
   *     params,
   *     cb
   *   } 
   */
  [types.RELEASE_LOANS](state, {
    vm,
    params,
    cb
  }) {
    vm.$ajax.post('loan/submitMakeLoanForm', vm.$postParams(params))
      .then(res => {
        vm.$notify({
          title: '成功',
          message: '放款成功',
          type: 'success'
        })
        if (cb) {
          cb()
        }
      })
      .catch(err => {
        vm.$notify.error({
          title: '错误',
          message: '发生了一个错误',
        })
        console.error(err)
      })
  }
}